﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.IO;
using System.Xml;
using System.Windows.Forms;

namespace Lapas.Common
{
    public class ExelUtilities
    {
        public static void ExportToExcel(DataSet source, string fileName, string header, string style, string footer)
        {

            System.IO.StreamWriter excelDoc;

            excelDoc = new System.IO.StreamWriter(fileName);
            string startExcelXML = "<xml version>\r\n<Workbook " +
                  "xmlns=\"urn:schemas-microsoft-com:office:spreadsheet\"\r\n" +
                  " xmlns:o=\"urn:schemas-microsoft-com:office:office\"\r\n " +
                  "xmlns:x=\"urn:schemas-    microsoft-com:office:" +
                  "excel\"\r\n xmlns:ss=\"urn:schemas-microsoft-com:" +
                  "office:spreadsheet\">\r\n <Styles>\r\n " +
                  "<Style ss:ID=\"Default\" ss:Name=\"Normal\">\r\n " +
                  "<Alignment ss:Vertical=\"Bottom\"/>\r\n <Borders/>" +
                  "\r\n <Font/>\r\n <Interior/>\r\n <NumberFormat/>" +
                  "\r\n <Protection/>\r\n </Style>\r\n " +
                  "<Style ss:ID=\"BoldColumn\">\r\n <Font " +
                  "x:Family=\"Swiss\" ss:Bold=\"1\"/>\r\n </Style>\r\n " +
                  "<Style     ss:ID=\"StringLiteral\">\r\n <NumberFormat" +
                  " ss:Format=\"@\"/>\r\n </Style>\r\n <Style " +
                  "ss:ID=\"Decimal\">\r\n <NumberFormat " +
                  "ss:Format=\"0\"/>\r\n </Style>\r\n " +
                  "<Style ss:ID=\"Integer\">\r\n <NumberFormat " +
                  "ss:Format=\"0\"/>\r\n </Style>\r\n <Style " +
                  "ss:ID=\"DateLiteral\">\r\n <NumberFormat " +
                  "ss:Format=\"mm/dd/yyyy;@\"/>\r\n </Style>\r\n " + style +
                  "</Styles>\r\n ";
            const string endExcelXML = "</Workbook>";

            int rowCount = 0;
            int sheetCount = 1;

            excelDoc.Write(startExcelXML);
            excelDoc.Write("<Worksheet ss:Name=\"Sheet" + sheetCount + "\">");
            excelDoc.Write("<Table>");
            //CHEN HEADER NEU CO VAO DAY:Header can dua vao dung dinh dang ExcelXML
            if (!string.IsNullOrEmpty(header))
            {
                excelDoc.Write(header);
            }
            excelDoc.Write("<Row>");
            for (int x = 0; x < source.Tables[0].Columns.Count; x++)
            {
                excelDoc.Write("<Cell ss:StyleID=\"BoldColumn\"><Data ss:Type=\"String\">");
                excelDoc.Write(source.Tables[0].Columns[x].ColumnName);
                excelDoc.Write("</Data></Cell>");
            }
            excelDoc.Write("</Row>");
            foreach (DataRow x in source.Tables[0].Rows)
            {
                rowCount++;
                //if the number of rows is > 64000 create a new page to continue output
                if (rowCount == 64000)
                {
                    rowCount = 0;
                    sheetCount++;
                    excelDoc.Write("</Table>");
                    excelDoc.Write(" </Worksheet>");
                    excelDoc.Write("<Worksheet ss:Name=\"Sheet" + sheetCount + "\">");
                    excelDoc.Write("<Table>");
                }
                excelDoc.Write("<Row>"); //ID=" + rowCount + "
                for (int y = 0; y < source.Tables[0].Columns.Count; y++)
                {
                    System.Type rowType;
                    rowType = x[y].GetType();
                    switch (rowType.ToString())
                    {
                        case "System.String":
                            string XMLstring = x[y].ToString();
                            XMLstring = XMLstring.Trim();
                            XMLstring = XMLstring.Replace("&", "&");
                            XMLstring = XMLstring.Replace(">", ">");
                            XMLstring = XMLstring.Replace("<", "<");
                            excelDoc.Write("<Cell ss:StyleID=\"StringLiteral\">" +
                                           "<Data ss:Type=\"String\">");
                            excelDoc.Write(XMLstring);
                            excelDoc.Write("</Data></Cell>");
                            break;
                        case "System.DateTime":
                            //Excel has a specific Date Format of YYYY-MM-DD followed by  
                            //the letter 'T' then hh:mm:sss.lll Example 2005-01-31T24:01:21.000
                            //The Following Code puts the date stored in XMLDate 
                            //to the format above
                            DateTime XMLDate = (DateTime)x[y];
                            string XMLDatetoString = ""; //Excel Converted Date
                            XMLDatetoString = XMLDate.Year.ToString() +
                                 "-" +
                                 (XMLDate.Month < 10 ? "0" +
                                 XMLDate.Month.ToString() : XMLDate.Month.ToString()) +
                                 "-" +
                                 (XMLDate.Day < 10 ? "0" +
                                 XMLDate.Day.ToString() : XMLDate.Day.ToString()) +
                                 "T" +
                                 (XMLDate.Hour < 10 ? "0" +
                                 XMLDate.Hour.ToString() : XMLDate.Hour.ToString()) +
                                 ":" +
                                 (XMLDate.Minute < 10 ? "0" +
                                 XMLDate.Minute.ToString() : XMLDate.Minute.ToString()) +
                                 ":" +
                                 (XMLDate.Second < 10 ? "0" +
                                 XMLDate.Second.ToString() : XMLDate.Second.ToString()) +
                                 ".000";
                            excelDoc.Write("<Cell ss:StyleID=\"DateLiteral\">" +
                                         "<Data ss:Type=\"DateTime\">");
                            excelDoc.Write(XMLDatetoString);
                            excelDoc.Write("</Data></Cell>");
                            break;
                        case "System.Boolean":
                            excelDoc.Write("<Cell ss:StyleID=\"StringLiteral\">" +
                                        "<Data ss:Type=\"String\">");
                            excelDoc.Write(x[y].ToString());
                            excelDoc.Write("</Data></Cell>");
                            break;
                        case "System.Int16":
                        case "System.Int32":
                        case "System.Int64":
                        case "System.Byte":
                            excelDoc.Write("<Cell ss:StyleID=\"Integer\">" +
                                    "<Data ss:Type=\"Number\">");
                            excelDoc.Write(x[y].ToString());
                            excelDoc.Write("</Data></Cell>");
                            break;
                        case "System.Decimal":
                        case "System.Double":
                            excelDoc.Write("<Cell ss:StyleID=\"Decimal\">" +
                                  "<Data ss:Type=\"Number\">");
                            excelDoc.Write(x[y].ToString());
                            excelDoc.Write("</Data></Cell>");
                            break;
                        case "System.DBNull":
                            excelDoc.Write("<Cell ss:StyleID=\"StringLiteral\">" +
                                  "<Data ss:Type=\"String\">");
                            excelDoc.Write("");
                            excelDoc.Write("</Data></Cell>");
                            break;
                        default:
                            throw (new Exception(rowType.ToString() + " not handled."));
                    }
                }
                excelDoc.Write("</Row>");
            }
            //CHEN FOOTER NEU CO VAO DAY
            if (!string.IsNullOrEmpty(footer))
            {
                excelDoc.Write(footer);
            }
            excelDoc.Write("</Table>");
            excelDoc.Write(" </Worksheet>");
            excelDoc.Write(endExcelXML);
            excelDoc.Close();
        }

        // 20090415 TriDM: viết thêm hàm để export ra đúng định dạng xml chuẩn
        public static void ExportToExcelXml(DataSet source, string fileName, string header, string style, string footer)
        {

            System.IO.StreamWriter excelDoc;

            excelDoc = new System.IO.StreamWriter(fileName);
            string startExcelXML = @"<?xml version=""1.0""?>" + "\r\n<Workbook " +
                  "xmlns=\"urn:schemas-microsoft-com:office:spreadsheet\"\r\n" +
                  " xmlns:o=\"urn:schemas-microsoft-com:office:office\"\r\n " +
                  "xmlns:x=\"urn:schemas-microsoft-com:office:" +
                  "excel\"\r\n xmlns:ss=\"urn:schemas-microsoft-com:" +
                  "office:spreadsheet\">\r\n <Styles>\r\n " +
                  "<Style ss:ID=\"Default\" ss:Name=\"Normal\">\r\n " +
                  "<Alignment ss:Vertical=\"Bottom\"/>\r\n <Borders/>" +
                  "\r\n <Font/>\r\n <Interior/>\r\n <NumberFormat/>" +
                  "\r\n <Protection/>\r\n </Style>\r\n " +
                  "<Style ss:ID=\"BoldColumn\">\r\n <Font " +
                  "x:Family=\"Swiss\" ss:Bold=\"1\"/>\r\n </Style>\r\n " +
                  "<Style ss:ID=\"StringLiteral\">\r\n <NumberFormat" +
                  " ss:Format=\"@\"/>\r\n </Style>\r\n <Style " +
                  "ss:ID=\"Decimal\">\r\n <NumberFormat " +
                  "ss:Format=\"0\"/>\r\n </Style>\r\n " +
                  "<Style ss:ID=\"Integer\">\r\n <NumberFormat " +
                  "ss:Format=\"0\"/>\r\n </Style>\r\n <Style " +
                  "ss:ID=\"DateLiteral\">\r\n <NumberFormat " +
                  "ss:Format=\"mm/dd/yyyy;@\"/>\r\n </Style>\r\n " + style +
                  "</Styles>\r\n ";
            const string endExcelXML = "</Workbook>";

            int rowCount = 0;
            int sheetCount = 1;

            excelDoc.Write(startExcelXML);
            excelDoc.Write("<Worksheet ss:Name=\"Sheet" + sheetCount + "\">");
            excelDoc.Write("<Table>");
            //CHEN HEADER NEU CO VAO DAY:Header can dua vao dung dinh dang ExcelXML
            if (header != string.Empty)
            {
                excelDoc.Write(header);
            }
            excelDoc.Write("<Row>");
            for (int x = 0; x < source.Tables[0].Columns.Count; x++)
            {
                excelDoc.Write("<Cell ss:StyleID=\"BoldColumn\"><Data ss:Type=\"String\">");
                excelDoc.Write(source.Tables[0].Columns[x].ColumnName);
                excelDoc.Write("</Data></Cell>");
            }
            excelDoc.Write("</Row>");
            foreach (DataRow x in source.Tables[0].Rows)
            {
                rowCount++;
                //if the number of rows is > 64000 create a new page to continue output
                if (rowCount == 64000)
                {
                    rowCount = 0;
                    sheetCount++;
                    excelDoc.Write("</Table>");
                    excelDoc.Write(" </Worksheet>");
                    excelDoc.Write("<Worksheet ss:Name=\"Sheet" + sheetCount + "\">");
                    excelDoc.Write("<Table>");
                }
                excelDoc.Write("<Row>"); //ID=" + rowCount + "
                for (int y = 0; y < source.Tables[0].Columns.Count; y++)
                {
                    System.Type rowType;
                    rowType = x[y].GetType();
                    switch (rowType.ToString())
                    {
                        case "System.String":
                            string XMLstring = x[y].ToString();
                            XMLstring = XMLstring.Trim();
                            XMLstring = XMLstring.Replace("&", "&");
                            XMLstring = XMLstring.Replace(">", ">");
                            XMLstring = XMLstring.Replace("<", "<");
                            excelDoc.Write("<Cell ss:StyleID=\"StringLiteral\">" +
                                           "<Data ss:Type=\"String\">");
                            excelDoc.Write(XMLstring);
                            excelDoc.Write("</Data></Cell>");
                            break;
                        case "System.DateTime":
                            //Excel has a specific Date Format of YYYY-MM-DD followed by  
                            //the letter 'T' then hh:mm:sss.lll Example 2005-01-31T24:01:21.000
                            //The Following Code puts the date stored in XMLDate 
                            //to the format above
                            DateTime XMLDate = (DateTime)x[y];
                            string XMLDatetoString = ""; //Excel Converted Date
                            XMLDatetoString = XMLDate.Year.ToString() +
                                 "-" +
                                 (XMLDate.Month < 10 ? "0" +
                                 XMLDate.Month.ToString() : XMLDate.Month.ToString()) +
                                 "-" +
                                 (XMLDate.Day < 10 ? "0" +
                                 XMLDate.Day.ToString() : XMLDate.Day.ToString()) +
                                 "T" +
                                 (XMLDate.Hour < 10 ? "0" +
                                 XMLDate.Hour.ToString() : XMLDate.Hour.ToString()) +
                                 ":" +
                                 (XMLDate.Minute < 10 ? "0" +
                                 XMLDate.Minute.ToString() : XMLDate.Minute.ToString()) +
                                 ":" +
                                 (XMLDate.Second < 10 ? "0" +
                                 XMLDate.Second.ToString() : XMLDate.Second.ToString()) +
                                 ".000";
                            excelDoc.Write("<Cell ss:StyleID=\"DateLiteral\">" +
                                         "<Data ss:Type=\"DateTime\">");
                            excelDoc.Write(XMLDatetoString);
                            excelDoc.Write("</Data></Cell>");
                            break;
                        case "System.Boolean":
                            excelDoc.Write("<Cell ss:StyleID=\"StringLiteral\">" +
                                        "<Data ss:Type=\"String\">");
                            excelDoc.Write(x[y].ToString());
                            excelDoc.Write("</Data></Cell>");
                            break;
                        case "System.Int16":
                        case "System.Int32":
                        case "System.Int64":
                        case "System.Byte":
                            excelDoc.Write("<Cell ss:StyleID=\"Integer\">" +
                                    "<Data ss:Type=\"Number\">");
                            excelDoc.Write(x[y].ToString());
                            excelDoc.Write("</Data></Cell>");
                            break;
                        case "System.Decimal":
                        case "System.Double":
                            excelDoc.Write("<Cell ss:StyleID=\"Decimal\">" +
                                  "<Data ss:Type=\"Number\">");
                            excelDoc.Write(x[y].ToString());
                            excelDoc.Write("</Data></Cell>");
                            break;
                        case "System.DBNull":
                            excelDoc.Write("<Cell ss:StyleID=\"StringLiteral\">" +
                                  "<Data ss:Type=\"String\">");
                            excelDoc.Write("");
                            excelDoc.Write("</Data></Cell>");
                            break;
                        default:
                            throw (new Exception(rowType.ToString() + " not handled."));
                    }
                }
                excelDoc.Write("</Row>");
            }
            //CHEN FOOTER NEU CO VAO DAY
            if (footer != string.Empty)
            {
                excelDoc.Write(footer);
            }
            excelDoc.Write("</Table>");
            excelDoc.Write(" </Worksheet>");
            excelDoc.Write(endExcelXML);
            excelDoc.Close();
        }

        public static void ExportGridViewToExcel(System.Windows.Forms.DataGridView Grid,bool allRows ,string header, string style)
        {
            if (Grid == null) return;
            if (Grid.SelectedRows.Count == 0)
            {
                DisplayMessage.ShowNotice("Hãy chọn dữ liệu cần Export");
                return;
            }
            using (System.Windows.Forms.SaveFileDialog saveFileDialog = new System.Windows.Forms.SaveFileDialog())
            {
                try
                {
                    saveFileDialog.Filter = "Excel files (*.xls)|*.xls|All files (*.*)|*.*";
                    //saveFileDialog.FileName = this.Text;
                    //saveFileDialog.Title = "Xuất ra " + this.Text;

                    if (saveFileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK && saveFileDialog.FileName.Length > 0)
                    {
                        DataSet dataSet = new DataSet();
                        ObjectAdapter objectAdapter = new ObjectAdapter();
                        DataTable dataTable = new DataTable();

                        //Lay toan bo du lieu trong grid xuat ra Excel
                        foreach (System.Windows.Forms.DataGridViewColumn column in Grid.Columns)
                        {

                            dataTable.Columns.Add(column.HeaderText, typeof(string));

                        }
                        if (allRows == false)
                        {
                            foreach (System.Windows.Forms.DataGridViewRow row in Grid.SelectedRows)
                            {
                                DataRow dataRow = dataTable.NewRow();

                                foreach (System.Windows.Forms.DataGridViewColumn column in Grid.Columns)
                                {
                                    // 20070927 TriDM: bo sung neu cot bi null thi tra ra string.Empty
                                    if (row.Cells[column.Index].Value == null)
                                    {
                                        dataRow[column.Index] = string.Empty;
                                    }
                                    else
                                    {
                                        dataRow[column.Index] = row.Cells[column.Index].Value.ToString();
                                    }
                                }
                                dataTable.Rows.Add(dataRow);
                            }
                        }
                        else
                        {
                            foreach (System.Windows.Forms.DataGridViewRow row in Grid.Rows)
                            {
                                DataRow dataRow = dataTable.NewRow();

                                foreach (System.Windows.Forms.DataGridViewColumn column in Grid.Columns)
                                {
                                    // 20070927 TriDM: bo sung neu cot bi null thi tra ra string.Empty
                                    if (row.Cells[column.Index].Value == null)
                                    {
                                        dataRow[column.Index] = string.Empty;
                                    }
                                    else
                                    {
                                        dataRow[column.Index] = row.Cells[column.Index].Value.ToString();
                                    }
                                }
                                dataTable.Rows.Add(dataRow);
                            }
                        }

                        //objectAdapter.Fill(dataSet, da);
                        dataSet.Tables.Add(dataTable);
                        ExelUtilities.ExportToExcel(dataSet, saveFileDialog.FileName, header, style, string.Empty);
                        DisplayMessage.ShowNotice("Export dữ liệu thành công");
                    }
                }
                catch (Exception ex)
                {
                    DisplayMessage.ShowError(ex.Message);
                }
            }
        }

        public static DataTable ImportFromExcel(string fileName)
        {
            DataTable dataImport = new DataTable();
            StreamReader streamReader;
            try
            {
                streamReader = new StreamReader(fileName);
            }
            catch (IOException exception)
            {
                DisplayMessage.ShowError(exception.Message);

                return null;

            }

            try
            {
                XmlDocument xmlDoc = new XmlDocument();
                xmlDoc.Load(streamReader);

                OExcelDocument template = new OExcelDocument(xmlDoc);
                XmlNode workbookNode = template.SelectNode(template.ExcelDocument, "Workbook");
                XmlNode workSheetNode = template.SelectNode(workbookNode, "WorkSheet");
                XmlNode tableObjectNode = template.SelectNode(workSheetNode, "Table");


                List<XmlNode> TemplateNode = new List<XmlNode>();


                // Doc tung hang, neu gap duoc STT thi bat dau nhap du lieu
                int dataRowNumber = -1, dataColumnNumber = -1;
                for (int rowNumber = 0; rowNumber < tableObjectNode.ChildNodes.Count; rowNumber++)
                {
                    XmlNode rowNode = tableObjectNode.ChildNodes[rowNumber];
                    for (int cellNumber = 0; cellNumber < rowNode.ChildNodes.Count; cellNumber++)
                    {
                        XmlNode dataNode = rowNode.ChildNodes[cellNumber];
                        if (dataNode.InnerText.ToUpper() == "STT")
                        {
                            dataRowNumber = rowNumber;
                            dataColumnNumber = cellNumber;
                            break;
                        }
                    }
                    if (dataRowNumber > -1) break;
                }

                if (dataRowNumber == -1)
                {
                    DisplayMessage.ShowError("Định dạng file không hợp lệ");
                    return null;
                }


                // Xac dinh ten cac cot
                // rowTitleNode la dong chua title cua file
                XmlNode rowTitleNode = tableObjectNode.ChildNodes[dataRowNumber];
                // Xac dinh so luong cot hop le: bang tong so cot cua row tru di tinh tu cot bat dau "STT"
                int dataImportColumnCount = rowTitleNode.ChildNodes.Count - dataColumnNumber;
                for (int cellNumber = dataColumnNumber + 1; cellNumber < dataImportColumnCount; cellNumber++)
                {
                    XmlNode dataTitleNode = rowTitleNode.ChildNodes[cellNumber];
                    string columnName = dataTitleNode.InnerText.ToUpper();
                    dataImport.Columns.Add(columnName);
                }

                // Load du lieu tu dong dataRowNumber+1
                for (int rowNumber = dataRowNumber + 1; rowNumber < tableObjectNode.ChildNodes.Count; rowNumber++)
                {
                    XmlNode rowNode = tableObjectNode.ChildNodes[rowNumber];
                    DataRow dataRow = dataImport.NewRow();

                    for (int count = 0; count < dataImportColumnCount; count++)
                    {
                        XmlNode dataNode = rowNode.ChildNodes[dataColumnNumber + count + 1];
                        if (dataNode != null)
                        {
                            dataRow[count] = dataNode.InnerText;
                        }
                    }
                    dataImport.Rows.Add(dataRow);
                }
            }
            catch
            {
                DisplayMessage.ShowError("Định dạng file không hợp lệ");
                return null;
            }
            return dataImport;
        }

        public static DataTable ImportFromExcel(string fileName, string firstTag)
        {
            DataTable dataImport = new DataTable();
            StreamReader streamReader;
            try
            {
                streamReader = new StreamReader(fileName);
            }
            catch (IOException ex)
            {
                throw ex;
            }            
            try
            {
                XmlDocument xmlDoc = new XmlDocument();
                xmlDoc.Load(streamReader);

                OExcelDocument template = new OExcelDocument(xmlDoc);
                XmlNode workbookNode = template.SelectNode(template.ExcelDocument, "Workbook");
                XmlNode workSheetNode = template.SelectNode(workbookNode, "WorkSheet");
                XmlNode tableObjectNode = template.SelectNode(workSheetNode, "Table");


                List<XmlNode> TemplateNode = new List<XmlNode>();


                // Doc tung hang, neu gap duoc STT thi bat dau nhap du lieu
                int dataRowNumber = -1, dataColumnNumber = -1;
                for (int rowNumber = 0; rowNumber < tableObjectNode.ChildNodes.Count; rowNumber++)
                {
                    XmlNode rowNode = tableObjectNode.ChildNodes[rowNumber];
                    for (int cellNumber = 0; cellNumber < rowNode.ChildNodes.Count; cellNumber++)
                    {
                        XmlNode dataNode = rowNode.ChildNodes[cellNumber];
                        if (dataNode.InnerText.ToUpper() == firstTag)
                        {
                            dataRowNumber = rowNumber;
                            dataColumnNumber = cellNumber;
                            break;
                        }
                    }
                    if (dataRowNumber > -1) break;
                }

                if (dataRowNumber == -1)
                {
                    throw new Exception("Định dạng file không hợp lệ");  
                }

                // Xac dinh ten cac cot
                // rowTitleNode la dong chua title cua file
                XmlNode rowTitleNode = tableObjectNode.ChildNodes[dataRowNumber];
                // Xac dinh so luong cot hop le: bang tong so cot cua row tru di tinh tu cot bat dau "STT"
                int dataImportColumnCount = rowTitleNode.ChildNodes.Count - dataColumnNumber;
                for (int cellNumber = dataColumnNumber; cellNumber < dataImportColumnCount; cellNumber++)
                {
                    XmlNode dataTitleNode = rowTitleNode.ChildNodes[cellNumber];
                    string columnName = dataTitleNode.InnerText.ToUpper();
                    dataImport.Columns.Add(columnName);
                }

                // Load du lieu tu dong dataRowNumber+1
                for (int rowNumber = dataRowNumber + 1; rowNumber < tableObjectNode.ChildNodes.Count; rowNumber++)
                {
                    XmlNode rowNode = tableObjectNode.ChildNodes[rowNumber];  
                    //Loại bỏ kí tự trắng
                    if(string.IsNullOrEmpty(rowNode.ChildNodes[dataColumnNumber].InnerText)) continue;
                    DataRow dataRow = dataImport.NewRow();
                    for (int count = 0; count < dataImportColumnCount; count++)
                    {                        
                        XmlNode dataNode = rowNode.ChildNodes[dataColumnNumber + count];
                        if (dataNode != null)
                        {
                            dataRow[count] = dataNode.InnerText;
                        }
                    }
                    dataImport.Rows.Add(dataRow);
                }
            }
            catch
            {
                throw new ApplicationException("Định dạng file không hợp lệ");                            
            }
            return dataImport;
        }        
    }
}
